{% extends "base.html" %}

{% block title %}用户管理{% endblock %}

{% block page_title %}用户管理{% endblock %}

{% block extra_css %}
<style>
.user-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
}

.user-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
}

.user-card {
    background: white;
    border-radius: var(--border-radius);
    padding: 20px;
    box-shadow: var(--box-shadow);
}

.user-card h3 {
    color: var(--secondary-color);
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.user-status {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8em;
}

.user-status.active {
    background: #e8f5e9;
    color: #2e7d32;
}

.user-status.inactive {
    background: #ffebee;
    color: #c62828;
}

.user-info {
    margin-bottom: 15px;
}

.user-info p {
    margin: 8px 0;
    color: var(--text-color);
}

.user-actions {
    display: flex;
    gap: 10px;
}

.modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
}

.modal-content {
    position: relative;
    background: white;
    width: 90%;
    max-width: 500px;
    margin: 50px auto;
    padding: 30px;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
}

.modal-header {
    margin-bottom: 20px;
}

.modal-header h2 {
    color: var(--secondary-color);
}

.form-group {
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    margin-bottom: 8px;
    color: var(--secondary-color);
}

.form-group input,
.form-group select {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.form-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}

.role-list {
    margin: 20px 0;
}

.role-item {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
}

.role-item h3 {
    color: var(--secondary-color);
    margin-bottom: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #ddd;
}

.permission-list {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 10px;
}

.permission-item {
    display: flex;
    align-items: center;
}

.permission-item label {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
}

.permission-item input[type="checkbox"] {
    width: 16px;
    height: 16px;
}

.close-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    background: none;
    border: none;
    color: var(--secondary-color);
    cursor: pointer;
    font-size: 1.2em;
}

.close-btn:hover {
    color: var(--primary-color);
}
</style>
{% endblock %}

{% block content %}
<div class="user-header">
    <button class="btn btn-primary" onclick="showAddUserModal()">
        <i class="fas fa-user-plus"></i> 添加用户
    </button>
    <button class="btn btn-secondary" onclick="showRoleManagementModal()">
        <i class="fas fa-user-tag"></i> 角色权限管理
    </button>
</div>

<div class="user-list">
    {% for user in users %}
    <div class="user-card">
        <h3>
            {{ user.username }}
            <span class="user-status {% if user.is_active %}active{% else %}inactive{% endif %}">
                {{ '在线' if user.is_active else '离线' }}
            </span>
        </h3>
        <div class="user-info">
            <p><i class="fas fa-envelope"></i> {{ user.email }}</p>
            <p><i class="fas fa-user-tag"></i> 角色：{{ user.role }}</p>
            <p><i class="fas fa-clock"></i> 创建时间：{{ user.created_at|datetime }}</p>
        </div>
        <div class="user-actions">
            <button class="btn btn-primary" onclick="editUser({{ user.id }})">
                <i class="fas fa-edit"></i> 编辑
            </button>
            <button class="btn btn-danger" onclick="deleteUser({{ user.id }})">
                <i class="fas fa-trash"></i> 删除
            </button>
        </div>
    </div>
    {% endfor %}
</div>

<!-- 角色权限管理模态框 -->
<div id="role-management-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-user-tag"></i> 角色权限管理</h2>
            <button class="close-btn" onclick="hideRoleManagementModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="role-list">
            {% for role in roles %}
            <div class="role-item">
                <h3>{{ role.name }}</h3>
                <div class="permission-list">
                    {% for permission in all_permissions %}
                    <div class="permission-item">
                        <label>
                            <input type="checkbox" 
                                   name="permission" 
                                   value="{{ permission }}"
                                   {% if permission in role.permissions %}checked{% endif %}
                                   onchange="updateRolePermission('{{ role.name }}', '{{ permission }}', this.checked)">
                            <span>{{ permission_names[permission] }}</span>
                        </label>
                    </div>
                    {% endfor %}
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div id="add-user-modal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2><i class="fas fa-user-plus"></i> 添加用户</h2>
        </div>
        <form id="add-user-form">
            <div class="form-group">
                <label><i class="fas fa-user"></i> 用户名</label>
                <input type="text" name="username" required>
            </div>
            <div class="form-group">
                <label><i class="fas fa-envelope"></i> 邮箱</label>
                <input type="email" name="email" required>
            </div>
            <div class="form-group">
                <label><i class="fas fa-key"></i> 密码</label>
                <input type="password" name="password" required>
            </div>
            <div class="form-group">
                <label><i class="fas fa-user-tag"></i> 角色</label>
                <select name="role" required>
                    <option value="admin">管理员</option>
                    <option value="manager">经理</option>
                    <option value="viewer">查看者</option>
                </select>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-secondary" onclick="hideAddUserModal()">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function showAddUserModal() {
    document.getElementById('add-user-modal').style.display = 'block';
}

function hideAddUserModal() {
    document.getElementById('add-user-modal').style.display = 'none';
}

document.getElementById('add-user-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    showLoading();
    
    const formData = new FormData(e.target);
    const data = {
        username: formData.get('username'),
        email: formData.get('email'),
        password: formData.get('password'),
        role: formData.get('role')
    };
    
    try {
        const response = await fetch('/api/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        if (response.ok) {
            window.location.reload();
        } else {
            const error = await response.json();
            alert(error.error || '添加用户失败');
        }
    } catch (error) {
        alert('添加用户失败');
    } finally {
        hideLoading();
    }
});

async function editUser(userId) {
    // 实现编辑用户的功能
    const role = prompt('请输入新的角色 (admin/manager/viewer)：');
    if (!role) return;
    
    try {
        const response = await fetch(`/api/users/${userId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ role })
        });
        
        if (response.ok) {
            window.location.reload();
        } else {
            alert('更新用户失败');
        }
    } catch (error) {
        alert('更新用户失败');
    }
}

async function deleteUser(userId) {
    if (!confirm('确定要删除此用户吗？')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/users/${userId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            window.location.reload();
        } else {
            alert('删除用户失败');
        }
    } catch (error) {
        alert('删除用户失败');
    }
}

function showRoleManagementModal() {
    document.getElementById('role-management-modal').style.display = 'block';
}

function hideRoleManagementModal() {
    document.getElementById('role-management-modal').style.display = 'none';
}

async function updateRolePermission(roleName, permission, isChecked) {
    try {
        const response = await fetch(`/api/roles/${roleName}/permissions`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                permission: permission,
                action: isChecked ? 'add' : 'remove'
            })
        });
        
        if (!response.ok) {
            throw new Error('更新权限失败');
        }
    } catch (error) {
        alert(error.message);
        // 恢复复选框状态
        event.target.checked = !isChecked;
    }
}
</script>
{% endblock %} 